package yanyan.com.tochar.funsactivity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.files.DialogFileChooserExtKt;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;


import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import io.microshow.rxffmpeg.RxFFmpegInvoke;
import io.microshow.rxffmpeg.RxFFmpegSubscriber;
import yanyan.com.tochar.R;

import yanyan.com.tochar.adpter.FullyGridLayoutManager;
import yanyan.com.tochar.adpter.GridImageAdapter;
import yanyan.com.tochar.utils.CoreUtil;
import yanyan.com.tochar.utils.EmptyUtils;
import yanyan.com.tochar.utils.PictureSelectUtil;
import yanyan.com.tochar.utils.ProgressDiaolog;
import yanyan.com.tochar.utils.ToastUtil;

import static android.os.Environment.getExternalStorageDirectory;

public class FunsGetAndPutVoiceActivity extends Activity implements CompoundButton.OnCheckedChangeListener {
    private RecyclerView recyclerView;
    private GridImageAdapter adapter;
    private List imgList = new ArrayList<>();//图片集合
    private ProgressDiaolog diaolog = null;
    private RadioButton getVoice, putVoice;
    private LinearLayout resLayout;
    private TextView resPath;
    private LinearLayout fileSelectLayout;
    private String selectFilePathStr;
    private EditText selectFileEd;
    private String resPathStr;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_funs_get_and_put_voice);
        recyclerView = findViewById(R.id.get_and_put_voice_recycler);

        getVoice = findViewById(R.id.get_and_put_voice_get);
        putVoice = findViewById(R.id.get_and_put_voice_put);
        getVoice.setOnCheckedChangeListener(this);
        putVoice.setOnCheckedChangeListener(this);

        resLayout = findViewById(R.id.get_and_put_voice_res_layout);

        resPath = findViewById(R.id.get_and_put_voice_res_path);

        fileSelectLayout = findViewById(R.id.get_and_put_voice_file_layout);

        selectFileEd = findViewById(R.id.get_and_put_voice_file_path);


        //初始化图片选择
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(manager);
        adapter = new GridImageAdapter(this, new GridImageAdapter.onAddPicClickListener() {
            @Override
            public void onAddPicClick() {
                PictureSelectUtil.selectVideo(FunsGetAndPutVoiceActivity.this, 3306);
            }
        });
        adapter.setList(imgList);
        adapter.setSelectMax(1);
        recyclerView.setAdapter(adapter);
        //统计各功能
        CoreUtil.statisticalFuns(this, "funs_get_put_voice");

    }

    /**
     * 选择图片事件
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            imgList = PictureSelector.obtainMultipleResult(data);
            adapter.setList(imgList);
            adapter.notifyDataSetChanged();
        }
    }


    public void getAndPut(View view) {
        if (imgList.size() > 0) {
            resPathStr="";
            LocalMedia localMedia = (LocalMedia) imgList.get(0);
            String path;
            if (CoreUtil.isAndroidQ()) {
                path = localMedia.getAndroidQToPath();
            } else {
                path = localMedia.getPath();
            }
            boolean activated = getVoice.isChecked();
            if (activated) {
                resLayout.setVisibility(View.GONE);
                getVoiceByVideo(path);
            } else {
                String voicePath = selectFileEd.getText().toString();
                if (EmptyUtils.isNotEmpty(voicePath)) {
                    boolean isMp3 = voicePath.endsWith("mp3");
                    if (isMp3) {
                        putVoiceByVideo(path, voicePath);
                    } else {
                        ToastUtil.showLongToast(this, "请选择mp3格式的音频");
                    }
                } else {
                    ToastUtil.showLongToast(this, "请选择音频文件");
                }

            }
        } else {
            ToastUtil.showLongToast(this, "您还没有选择视频");
        }
    }


    /**
     * 提取视频中的音频
     *
     * @param videoPath
     * @return
     */
    public String getVoiceByVideo(String videoPath) {
        File videoFile = new File(videoPath);
        String name = videoFile.getName();
        diaolog = new ProgressDiaolog(this, "正在提取音频");
        diaolog.show();
        //ffmpeg -i temp.mp4 -f mp3 -vn temp.mp3
        String cachePath = PictureSelectUtil.getFilePath(this) + name + ".mp3";
        String ins = "ffmpeg -y -i ";
        ins += videoPath;
        ins += " -f mp3 -vn ";
        ins += cachePath;
        excuteFfmpeg(ins, new FunsGetAndPutVoiceActivity.OnVideoState() {
            @Override
            public void finsh() {
                resLayout.setVisibility(View.VISIBLE);
                resPath.setText("文件已保存到：" + cachePath);
                resPathStr=cachePath;
                diaolog.hide();
            }
        });
        return cachePath;
    }

    public void putVoiceByVideo(String videoPath, String voicePath) {
        //ffmpeg -i  c:/db/1.mp3  -i c:/db/annew.mp4  c:/db/last.mp4
        File videoFile = new File(videoPath);
        String name = videoFile.getName();
        diaolog = new ProgressDiaolog(this, "正在合并音频");
        diaolog.show();
        //ffmpeg -i temp.mp4 -f mp3 -vn temp.mp3
        String cachePath = PictureSelectUtil.getFilePath(this) + name;
        String ins = "ffmpeg -y -i ";
        ins += voicePath;
        ins += " -i ";
        ins += videoPath;
        ins += " ";
        ins += cachePath;
        excuteFfmpeg(ins, new FunsGetAndPutVoiceActivity.OnVideoState() {
            @Override
            public void finsh() {
                resLayout.setVisibility(View.VISIBLE);
                resPath.setText("文件已保存到：" + cachePath);
                resPathStr=cachePath;
                diaolog.hide();
            }
        });
    }


    /**
     * 执行ffmpeg代码
     *
     * @param text
     * @param onVideoState
     */
    public void excuteFfmpeg(String text, OnVideoState onVideoState) {
        RxFFmpegInvoke.getInstance().setDebug(true);
        String[] commands = text.split(" ");
        RxFFmpegInvoke.getInstance().runCommandRxJava(commands).subscribe(new RxFFmpegSubscriber() {
            @Override
            public void onFinish() {
                onVideoState.finsh();
            }

            @Override
            public void onProgress(int progress, long progressTime) {
            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onError(String message) {
                ToastUtil.showLongToast(FunsGetAndPutVoiceActivity.this, "错误：" + message);
            }
        });

    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        int id = buttonView.getId();
        if (id == R.id.get_and_put_voice_get) {
            if (isChecked) {
                fileSelectLayout.setVisibility(View.GONE);
            }

        } else {
            if (isChecked) {
                fileSelectLayout.setVisibility(View.VISIBLE);
            }

        }

    }

    public interface OnVideoState {
        public void finsh();
    }


    /**
     * 选择音频文件
     *
     * @param view
     */
    public void selectPutMp3File(View view) {
        selectFile();
    }


    public void selectFile(String isQ) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("audio/mp3");
        this.startActivityForResult(intent, 3306);
    }

    public void selectFile() {
        MaterialDialog dialog = new MaterialDialog(this, MaterialDialog.getDEFAULT_BEHAVIOR());
        dialog.title(R.string.selectFile, "选择音频文件");
        if (CoreUtil.isAndroidQ()) {
            selectFile("");
            return;
        }

        DialogFileChooserExtKt.fileChooser(dialog, getExternalStorageDirectory(), file -> {
                    return (file.getName().endsWith(""));
                },
                true, R.string.files_folder_hint, false, null,
                (materialDialog, file) -> {
                    Toast.makeText(this, file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                    selectFilePathStr = file.getAbsolutePath();
                    return null;
                });


        dialog.positiveButton(R.string.selectFile, null, materialDialog -> {
            if (EmptyUtils.isNotEmpty(selectFilePathStr)) {
                if (selectFilePathStr.endsWith("mp3")) {
                    selectFileEd.setText(selectFilePathStr);
                } else {
                    selectFilePathStr = null;
                    ToastUtil.showLongToast(this, "请选择mp3格式的文件");
                }

            } else {
                Toast.makeText(this, "点击了确定111111111111111", Toast.LENGTH_SHORT).show();
            }

            return null;
        });


        dialog.negativeButton(android.R.string.cancel, null, materialDialog -> {
            selectFilePathStr = "null";
            return null;
        });
        dialog.show();
    }


    public void openResPutVideo(View view){
        if(EmptyUtils.isEmpty(resPathStr)){
            ToastUtil.showLongToast(this,"请先生成");
            return;
        }
        boolean checked = putVoice.isChecked();
        if(checked){
            openVideo(resPathStr,"voice/*");
        }else {
            openVideo(resPathStr,"video/*");
        }
    }


    /**
     * 打开自带浏览器播放视频
     * @param path
     */
    private void openVideo(String path,String type){
        Intent intent=new Intent(Intent.ACTION_VIEW);
        File file=new File(path);
        Uri uri=Uri.fromFile(file);
//        intent.setDataAndType(uri,"video/*");
        intent.setDataAndType(uri,type);
        startActivity(intent);
    }

}
